// ignore_for_file: depend_on_referenced_packages

import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:tiktokadult/config/config.dart';
import 'package:tiktokadult/hj_utils/global.dart';
import 'package:tiktokadult/hj_utils/video_cmd_helper.dart';
import 'package:image_pickers/image_pickers.dart';
import 'package:mime/mime.dart';

import '../assets_tool/app_colors.dart';
import '../tools_base/global_store/store.dart';
import 'file_util.dart';

/// 视频工具类
class VideoUtils {
  ///获取视频mimeType
  static Future<String> getMimeType(String localPath) async {
    String mimeTypeStr = 'mp4';
    try {
      mimeTypeStr = lookupMimeType(localPath) ?? "";
    } on PlatformException {
      return '';
    }
    return mimeTypeStr;
  }

  ///选择图片
  static Future<List<String>> pickImg(int needCount) async {
    List<String> ret = [];
    var listMedia = await ImagePickers.pickerPaths(
      uiConfig: UIConfig(uiThemeColor: AppColors.primaryColor),
      galleryMode: GalleryMode.image,
      selectCount: needCount,
      showCamera: true,
    );
    if (listMedia.isEmpty == true) return ret;

    if (Platform.isAndroid) {
      for (var index = 0; index < listMedia.length; index++) {
        var path = listMedia[index].path;
        if (path != null) {
          ret.add(path);
        }
      }
    } else {
      for (var index = 0; index < listMedia.length; index++) {
        var path = listMedia[index].path;
        var file = File(path!);
        var size = await file.readAsBytes();
        //大于300kb的图需要压缩
        if ((size.length / 1024) > 300) {
          var compressFile = await FlutterNativeImage.compressImage(path, percentage: 40, quality: 50);
          path = compressFile.path;
        }
        if (path != null) {
          ret.add(path);
        } else {
          showToast("添加图片失败");
        }
      }
    }
    return ret;
  }

  ///获取视频时长
  static Future<int> getVideoDuration(String localPath) async {
    const platform = MethodChannel(Config.naticeChannel);
    int duration = 0;
    try {
      duration = await platform.invokeMethod("getVideoDuration", {'filePath': localPath});
    } on PlatformException {
      return duration;
    }
    return duration;
  }

  ///获取视频分辨率
  static Future<String> getVideoResolution(String localPath) async {
    const platform = MethodChannel(Config.naticeChannel);
    String resolutionStr = '';
    try {
      resolutionStr = await platform.invokeMethod("getVideoResolution", {'filePath': localPath});
    } on PlatformException {
      return '';
    }
    return resolutionStr;
  }

  ///获取视频高度
  static Future<String> getVideoHeight(String localPath) async {
    const platform = MethodChannel(Config.naticeChannel);
    String heightStr = '';
    try {
      heightStr = await platform.invokeMethod("getVideoHeight", {'filePath': localPath});
    } on PlatformException {
      return '';
    }
    return heightStr;
  }

  ///获取视频宽高比
  static Future<String> getVideoRatio(String localPath) async {
    const platform = MethodChannel(Config.naticeChannel);
    String ratioStr = '';
    try {
      ratioStr = await platform.invokeMethod("getVideoRatio", {'filePath': localPath});
    } on PlatformException {
      return '';
    }
    return ratioStr;
  }

  ///获取视频封面
  static Future<String> getVideoCoverPath(String localPath) async {
    const platform = MethodChannel(Config.naticeChannel);
    String coverPath = '';
    try {
      coverPath = await platform.invokeMethod("saveCoverInLocal", {'filePath': localPath});
    } on PlatformException {
      return '';
    }
    return coverPath;
  }

  ///获取视频比特率
  static Future<String> getVideoBitrate(String localPath) async {
    const platform = MethodChannel(Config.naticeChannel);
    String bitrate = '';
    try {
      bitrate = await platform.invokeMethod("getVideoBitrate", {'filePath': localPath});
    } on PlatformException {
      return '';
    }
    return bitrate;
  }

  /// 获取视频信息
  static Future<MediaInfo?> getMediaInfo(String localPath) async {
    if (!FileUtil.isFileExist(localPath)) return Future.value(null);
    MediaInfo videoInfo = MediaInfo();
    videoInfo.videoHeight = int.parse(await getVideoHeight(localPath));
    videoInfo.resolution = await getVideoResolution(localPath);
    videoInfo.ratio = double.parse(await getVideoRatio(localPath));
    videoInfo.playTime = await getVideoDuration(localPath);
    videoInfo.bitrate = await getVideoBitrate(localPath);
    videoInfo.size = FileUtil.getFileSize(localPath);
    videoInfo.mimeType = await getMimeType(localPath);
    return videoInfo;
  }

  ///根据ffmpeg获取视频信息
  static Future<Map<String, dynamic>?> getVideoInfo(String? localPath) async {
    if (localPath == null || localPath.isEmpty) return Future.value(null);
    Map<String, dynamic> infoMap = {};
    var videoInfo = await VideoCmdHelper().getVideoInfos(localPath);
    int size = videoInfo["size"] ?? 0;
    if (size == 0) {
      return Future.value(null);
    }
    int duration = videoInfo["playTime"] ?? 0;
    int width = videoInfo["width"] ?? 0;
    int height = videoInfo["height"] ?? 0;
    //bytes
    infoMap['size'] = size;
    infoMap['width'] = width;
    infoMap['height'] = height;
    //width/height
    infoMap['ratio'] = width * 1.0 / height;
    //seconds
    infoMap['playTime'] = duration ~/ 1000;
    infoMap['bitrate'] = videoInfo["bitrate"];
    return infoMap;
  }

  static bool isBeforeToday() {
    var startDate = globalStore.getMe()?.goldVideoFreeExpire ?? "";
    if (startDate.isEmpty) return true;
    var endDate = DateTime.now();
    try {
      return endDate.isBefore(DateTime.parse(startDate));
    } catch (e) {
      return true;
    }
  }
}

class MediaInfo {
  int? size;
  String? resolution;
  int? videoHeight;
  double? ratio;
  int? playTime;
  String? bitrate;
  String? mimeType;
}
